#!/bin/bash

# 假设输入文件 '2.sh' 位于当前工作目录 (即执行此脚本的目录)
INPUT_FILE="./2.sh"
OUTPUT_FILE="/data/kuaicdn/network/ipv4_static_ip.txt"
OUTPUT_DIR=$(dirname "$OUTPUT_FILE")

# --- 辅助函数: 初始化目录结构 ---
initialize_environment() {
    echo "--- 1. Initializing directory structure ---"
    # 1. 清理旧的符号链接（如果存在）
    if [ -L ~/network ]; then
        echo "Removing existing symlink: ~/network"
        rm -f ~/network
    fi

    # 2. 确保目标目录和文件存在
    if [ ! -d "$OUTPUT_DIR" ]; then
        echo "Creating directory: $OUTPUT_DIR"
        mkdir -p "$OUTPUT_DIR"
        if [ $? -ne 0 ]; then
            echo "Error: Failed to create output directory '$OUTPUT_DIR'" >&2
            exit 1
        fi
    fi

    # 3. 如果目标文件不存在，则创建它（原函数逻辑）
    if [ ! -f "$OUTPUT_FILE" ]; then
        echo "Creating empty file: $OUTPUT_FILE"
        echo '' > "$OUTPUT_FILE"
    fi
    
    # 4. 创建 ~/network 符号链接指向 /data/kuaicdn/network
    ln -sf "$OUTPUT_DIR" ~/network
    echo "Symlink ~/network -> $OUTPUT_DIR created."
}

# --- 2. 获取网络接口信息 ---
echo -e "\n--- 2. Getting Network Interface Info ---"
nic=$(ip -br a | awk '$2 == "UP" && $1 !~ /^lo/ && $1 !~ /^br-/ {print $1}' | head -n 1)
if [ -z "$nic" ]; then
    echo "Error: No UP network interface found" >&2
    exit 1
fi
echo "Primary UP NIC found: $nic"

# 尝试确定网桥名称 (如果使用动态命名)
bridge=$(ip -br a | awk -v nic="$nic" '$1 ~ "^br-if-" nic "$" && $2 == "UP" {print $1}')
if [ -z "$bridge" ]; then
    # 如果没有找到匹配的动态网桥，则使用一个默认或保持为空，让 awk 使用固定值或动态推断
    bridge="br-eth5" # 沿用原 awk 中硬编码的值作为默认
    echo "No matching bridge found, defaulting to: $bridge"
fi


# --- 3. 获取 IPMI IP 地址 ---
echo -e "\n--- 3. Getting IPMI IP Address ---"
if ! command -v ipmitool &> /dev/null; then
    echo "Error: ipmitool is not installed or not in PATH." >&2
    exit 1
fi
# 假设 IPMI LAN 2 是要检查的接口
ipmi_ip=$(ipmitool lan print 2>/dev/null | awk '/IP Address +:/{print $NF}')
if [ -z "$ipmi_ip" ]; then
    echo "Error: Failed to retrieve IP address from ipmitool" >&2
    exit 1
fi
echo "IPMI IP found: $ipmi_ip"

# --- 4. 检查输入文件是否存在 ---
if [ ! -f "$INPUT_FILE" ]; then
    echo "Error: Input file '$INPUT_FILE' not found in the current directory." >&2
    exit 1
fi

# --- 5. 生成配置文件 (核心修改) ---
echo -e "\n--- 4. Generating Configuration File ---"
echo "Generating configuration file using IPMI IP: $ipmi_ip and primary NIC: $nic..."

awk -F'\t' -v ipmi_ip="$ipmi_ip" -v nic="$nic" -v bridge="$bridge" '
BEGIN {
    srand()
    split(ipmi_ip, ip, ".")
    ip2=ip[2]
    ip3=ip[3]
}
{
    # 提取字段 (假设输入文件 2.sh 的字段分隔符是制表符 \t)
    id=$1          # VLAN ID
    ip_mask=$2     # IP Mask
    gateway=$3     # Gateway
    port=$4        # MAX_TX/MAX_RX (Port value)

    # 生成 3 个随机数 (10-99)
    rand1=int(10 + rand() * 90)
    rand2=int(10 + rand() * 90)
    rand3=int(10 + rand() * 90)

    # 格式化 MAC 地址 (注意：rand3 格式化为两位十进制 %02d)
    mac=sprintf("66:%d:%d:%d:%d:%02d", ip2, ip3, rand1, rand2, rand3)

    # 输出目标格式：使用制表符 \t 分隔
    printf "MAC=%s\tVLAN=%d\tIPV4_MASK=%s\tIPV4_GATEWAY=%s\tNIC=%s\tBRIDGE=%s\tMAX_TX=%d\tMAX_RX=%d\tENABLE=1\n", mac, id, ip_mask, gateway, nic, bridge, port, port
}' "$INPUT_FILE" > "$OUTPUT_FILE"

if [ $? -eq 0 ]; then
    echo "Configuration file successfully written to $OUTPUT_FILE"
else
    echo "Error: awk command failed during configuration generation." >&2
    exit 1
fi

# --- 6. 打印文件内容 ---
echo -e "\n--- 5. Content of $OUTPUT_FILE ---"
cat "$OUTPUT_FILE"
echo "--------------------------------------------------"